//
//  GoodsDetailViewController.m
//  yunbaolive
//
//  Created by IOS1 on 2019/8/28.
//  Copyright © 2019 cat. All rights reserved.
//

#import "GoodsDetailViewController.h"
#import "ShopCell.h"
#import "ShopDetailVC.h"

@interface GoodsDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    int page;
    NSMutableArray *infoArray;
    UIView *headerView;
    UIButton *allreturnBtn;
    UIButton *leftBtn;
}
@property (nonatomic,strong) UICollectionView *shopCollectView;


@end

@implementation GoodsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    self.titleL.text = minstr([_goosDic valueForKey:@"name"]);
    infoArray = [NSMutableArray array];
    page = 1;
    [self creatUI];
    [self requestData];
}
- (void)creatUI{
    NSString *nameStr = minstr([_goosDic valueForKey:@"name"]);
    NSString *contentStr = minstr([_goosDic valueForKey:@"des"]);
    CGFloat nameHeight = [PublicObj heightOfString:nameStr andFont:[UIFont boldSystemFontOfSize:15] andWidth:_window_width-40] + 5;
    CGFloat contentHeight = [PublicObj  heightOfString:contentStr andFont:SYS_Font(13) andWidth:_window_width-40] + 5;

    headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_width + 110 + nameHeight + contentHeight + 30 + 15)];
    headerView.backgroundColor = RGB_COLOR(@"#f0f0f0", 1);
    
    UIImageView *thumbImgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_width)];
    [thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([_goosDic valueForKey:@"thumb"])]];
    thumbImgV.contentMode = UIViewContentModeScaleAspectFill;
    thumbImgV.clipsToBounds = YES;
    [headerView addSubview:thumbImgV];
    
    UIView *goodsView = [[UIView alloc]initWithFrame:CGRectMake(0, thumbImgV.bottom, _window_width, nameHeight + contentHeight + 30 + 15)];
    goodsView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:goodsView];
    
    UILabel *goodsPriceL = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, _window_width-40, 30)];
    goodsPriceL.text = [NSString stringWithFormat:@"¥%@",minstr([_goosDic valueForKey:@"price"])];
    goodsPriceL.textColor = RGB_COLOR(@"#FB483A", 1);
    goodsPriceL.font = [UIFont boldSystemFontOfSize:15];
    [goodsView addSubview:goodsPriceL];
    UILabel *goodsNameL = [[UILabel alloc]initWithFrame:CGRectMake(20, goodsPriceL.bottom+5, _window_width-40, nameHeight)];
    goodsNameL.text = nameStr;
    goodsNameL.textColor = RGB_COLOR(@"#323232", 1);
    goodsNameL.font = [UIFont boldSystemFontOfSize:15];
    goodsNameL.numberOfLines = 0;
    [goodsView addSubview:goodsNameL];
    UILabel *goodsContentL = [[UILabel alloc]initWithFrame:CGRectMake(20, goodsNameL.bottom+5, _window_width-40, contentHeight)];
    goodsContentL.text = contentStr;
    goodsContentL.textColor = RGB_COLOR(@"#969696", 1);
    goodsContentL.font = SYS_Font(13);
    goodsContentL.numberOfLines = 0;
    [goodsView addSubview:goodsContentL];

    UIView *shopView = [[UIView alloc]initWithFrame:CGRectMake(0, goodsView.bottom + 5, _window_width, 70)];
    shopView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:shopView];
    UIImageView *shopIconV = [[UIImageView alloc]initWithFrame:CGRectMake(20, 15, 40, 40)];
    [shopIconV sd_setImageWithURL:[NSURL URLWithString:minstr([_shopDic valueForKey:@"thumb"])]];
    shopIconV.layer.cornerRadius =5;
    shopIconV.layer.masksToBounds = YES;
    shopIconV.layer.borderColor = RGB_COLOR(@"#e6e6e6", 1).CGColor;
    shopIconV.layer.borderWidth = 1;
    [shopView addSubview:shopIconV];
    
    UILabel *shopNameL = [[UILabel alloc]initWithFrame:CGRectMake(shopIconV.right+ 12, shopIconV.top, _window_width-40, 20)];
    shopNameL.text = minstr([_shopDic valueForKey:@"name"]);
    shopNameL.textColor = RGB_COLOR(@"#323232", 1);
    shopNameL.font = [UIFont boldSystemFontOfSize:13];
    shopNameL.numberOfLines = 0;
    [shopView addSubview:shopNameL];
    UILabel *goodsNumL = [[UILabel alloc]initWithFrame:CGRectMake(shopIconV.right+ 12, shopIconV.centerY, _window_width-40, 20)];
    goodsNumL.text = [NSString stringWithFormat:YZMsg(@"在售商品 %@"),_goodsNums];
    goodsNumL.textColor = RGB_COLOR(@"#969696", 1);
    goodsNumL.font = SYS_Font(10);
    [shopView addSubview:goodsNumL];
    UIButton *doStoreBtn = [UIButton buttonWithType:0];
    doStoreBtn.frame = CGRectMake(_window_width-80, shopIconV.centerY-12, 70, 24);
    [doStoreBtn setTitle:YZMsg(@"进店逛逛") forState:0];
    [doStoreBtn setTitleColor:Normal_Color forState:0];
    [doStoreBtn addTarget:self action:@selector(doStoreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    doStoreBtn.layer.cornerRadius = 12;
    doStoreBtn.layer.masksToBounds = YES;
    doStoreBtn.layer.borderColor = Normal_Color.CGColor;
    doStoreBtn.layer.borderWidth = 1;
    doStoreBtn.titleLabel.font = [UIFont boldSystemFontOfSize:11];
    [shopView addSubview:doStoreBtn];

    
    UIView *hotView = [[UIView alloc]initWithFrame:CGRectMake(0, shopView.bottom + 5, _window_width, 30)];
    hotView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:hotView];
    UILabel *hotLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, _window_width-40, 30)];
    hotLabel.text = YZMsg(@"推荐商品");
    hotLabel.textColor = RGB_COLOR(@"#323232", 1);
    hotLabel.font = [UIFont boldSystemFontOfSize:13];
    [hotView addSubview:hotLabel];

    
    
    [self.view addSubview:self.shopCollectView];
    [self.view sendSubviewToBack:_shopCollectView];
    allreturnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    allreturnBtn.frame = CGRectMake(20,24 + statusbarHeight,40,40);
    allreturnBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 0, 10, 20);
    [allreturnBtn setImage:[UIImage imageNamed:@"navi_backImg"] forState:UIControlStateNormal];
    [allreturnBtn addTarget:self action:@selector(doReturn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:allreturnBtn];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-50-ShowDiff, _window_width, 50+ShowDiff)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    [PublicObj  lineViewWithFrame:CGRectMake(0, 0, _window_width, 0.5) andColor:RGB_COLOR(@"#f0f0f0", 1) andView:bottomView];
    if ([minstr([_shopDic valueForKey:@"uid"]) isEqual:[Config getOwnID]] && !_isFromGoods) {
        leftBtn = [UIButton buttonWithType:0];
        leftBtn.frame = CGRectMake(10, 5, (_window_width-25)/7*5, 40);
        if ([minstr([_goosDic valueForKey:@"status"]) isEqual:@"1"]) {
            [leftBtn setTitle:YZMsg(@"下架") forState:0];
            [leftBtn setBackgroundImage:[UIImage imageNamed:@"startLive_back"] forState:0];
        }else if ([minstr([_goosDic valueForKey:@"status"]) isEqual:@"-1"]) {
            [leftBtn setTitle:YZMsg(@"重新上架") forState:0];
            [leftBtn setBackgroundImage:[UIImage imageNamed:@"startLive_back"] forState:0];
        }else{
            [leftBtn setTitle:YZMsg(@"重新上架") forState:0];
            [leftBtn setBackgroundColor:RGB_COLOR(@"#C8C8C8", 1)];
            leftBtn.userInteractionEnabled = NO;
        }
        leftBtn.titleLabel.font = SYS_Font(15);
        leftBtn.layer.cornerRadius = 20;
        leftBtn.layer.masksToBounds = YES;
        [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:leftBtn];
        
        UIButton *rightBtn = [UIButton buttonWithType:0];
        rightBtn.frame = CGRectMake(leftBtn.right + 5, 5, (_window_width-25)/7*2, 40);
        [rightBtn setTitle:YZMsg(@"删除") forState:0];
        rightBtn.titleLabel.font = SYS_Font(15);
        [rightBtn setTitleColor:RGB_COLOR(@"#969696", 1) forState:0];
        rightBtn.layer.cornerRadius = 20;
        rightBtn.layer.masksToBounds = YES;
        rightBtn.layer.borderColor = RGB_COLOR(@"#969696", 1).CGColor;
        rightBtn.layer.borderWidth = 1;
        [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:rightBtn];

    }else{
        UIButton *buyBtn = [UIButton buttonWithType:0];
        [buyBtn setBackgroundImage:[UIImage imageNamed:@"startLive_back"] forState:0];
        buyBtn.frame = CGRectMake(10, 5, (_window_width-20), 40);
        [buyBtn setTitle:YZMsg(@"去购买") forState:0];
        buyBtn.titleLabel.font = SYS_Font(15);
        buyBtn.layer.cornerRadius = 20;
        buyBtn.layer.masksToBounds = YES;
        [buyBtn addTarget:self action:@selector(dobuy) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:buyBtn];

    }
}
- (void)dobuy{
    if ([minstr([_goosDic valueForKey:@"type"]) isEqual:@"1"]) {
        [PublicObj openWXMiniProgram:minstr([_goosDic valueForKey:@"href"])];
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:minstr([_goosDic valueForKey:@"href"])]];
    }

}
- (void)leftBtnClick{
    NSString *stauessss;
    if ([minstr([_goosDic valueForKey:@"status"]) isEqual:@"1"]) {
        stauessss = @"-1";
        UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"下架后用户将无法购买此款商品 确定要下架此款商品吗？") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [cancleAction setValue:RGB_COLOR(@"#969696", 1) forKey:@"_titleTextColor"];
        
        [alertContro addAction:cancleAction];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"下架") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self shangxiajiashangpin:stauessss];
        }];
        [sureAction setValue:Normal_Color forKey:@"_titleTextColor"];
        [alertContro addAction:sureAction];
        [self presentViewController:alertContro animated:YES completion:nil];

    }else{
        stauessss = @"1";
        [self shangxiajiashangpin:stauessss];
    }

}
- (void)shangxiajiashangpin:(NSString *)stauesss{
    
    [WYNetworking postWithUrl:@"Shop.UpStatus" Dic:@{@"goodsid":minstr([_goosDic valueForKey:@"id"]),@"status":stauesss} Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD showError:msg];
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            if ([minstr([infoDic valueForKey:@"status"]) isEqual:@"1"]) {
                [leftBtn setTitle:YZMsg(@"下架") forState:0];
            }else{
                [leftBtn setTitle:YZMsg(@"重新上架") forState:0];
            }
            
        }

        } Fail:^(id fail) {
            
     }];

}
- (void)rightBtnClick{
    UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"删除后店铺内将不再显示此款商品 确定要删除此款商品吗？") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [cancleAction setValue:RGB_COLOR(@"#969696", 1) forKey:@"_titleTextColor"];

    [alertContro addAction:cancleAction];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"删除") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [WYNetworking postWithUrl:@"Shop.DelGoods" Dic:@{@"goodsid":minstr([_goosDic valueForKey:@"id"])} Suc:^(int code, id info, NSString *msg) {
            [MBProgressHUD showError:msg];
            if (code == 0) {
                if (self.block) {
                    self.block();
                }
                [self doReturn];
                
            }

            } Fail:^(id fail) {
                
         }];

    }];
    [sureAction setValue:Normal_Color forKey:@"_titleTextColor"];
    [alertContro addAction:sureAction];
    [self presentViewController:alertContro animated:YES completion:nil];


}
- (void)doReturn{
//    [self.navigationController popViewControllerAnimated:YES];
}
- (UICollectionView *)shopCollectView{
    if (!_shopCollectView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
        flow.minimumLineSpacing = 7;
        flow.minimumInteritemSpacing = 7;
        flow.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7);
        flow.headerReferenceSize = CGSizeMake(_window_width, headerView.height);
        _shopCollectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, _window_width, _window_height-50-ShowDiff) collectionViewLayout:flow];
        [_shopCollectView registerNib:[UINib nibWithNibName:@"shopCell" bundle:nil] forCellWithReuseIdentifier:@"shopCELL"];
        [_shopCollectView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"goodDetaileHeaderV"];
        _shopCollectView.delegate =self;
        _shopCollectView.dataSource = self;
        _shopCollectView.backgroundColor = RGB_COLOR(@"#ffffff", 1);
//        _shopCollectView.mj_footer  = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//            page ++;
//            [self requestData];
//        }];
//        
//        _shopCollectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            page = 1;
//            [self requestData];
//            
//        }];
        
        if (@available(iOS 11.0, *)) {
            _shopCollectView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
    }
    return _shopCollectView;
}
- (void)requestData{
    
    [WYNetworking postWithUrl:@"Shop.GetRecomment"  Dic:@{@"touid":minstr([_shopDic valueForKey:@"uid"])} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            if (page == 1) {
                [infoArray removeAllObjects];
            }
            [infoArray addObjectsFromArray:info];
            [_shopCollectView reloadData];

        }

        } Fail:^(id fail) {
            
     }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return infoArray.count;
//    return 20;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopCell *cell = (ShopCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopCELL" forIndexPath:indexPath];
    NSDictionary *subDic = infoArray[indexPath.row];
    [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
    cell.titleL.text = minstr([subDic valueForKey:@"name"]);
    cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
    if (minstr([subDic valueForKey:@"old_price"]).length > 0) {
        cell.oldPriceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"old_price"])];
    }else{
        cell.oldPriceL.text = @"";
    }
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"goodDetaileHeaderV" forIndexPath:indexPath];
        
        header.backgroundColor = [UIColor whiteColor];
        [header addSubview:headerView];
        return header;
    }else{
        return nil;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *subDic = infoArray[indexPath.row];
    GoodsDetailViewController *vc = [[GoodsDetailViewController alloc]init];
    vc.goosDic = subDic;
    vc.shopDic = _shopDic;
    vc.goodsNums = _goodsNums;
    vc.block = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [collectionView.mj_header beginRefreshing];
        });
    };
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];

}

- (void)coverClickVideoid:(NSString *)videoid {
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y > 64+statusbarHeight) {
        self.naviView.hidden = NO;
        self.naviView.alpha = 1;
        allreturnBtn.hidden = YES;
        allreturnBtn.alpha = 0;
    }else{
        self.naviView.hidden = NO;
        self.naviView.alpha = scrollView.contentOffset.y/(64.00000+statusbarHeight);
        allreturnBtn.alpha = 1 - self.naviView.alpha;
        if (scrollView.contentOffset.y == 0) {
            self.naviView.hidden = YES;
            allreturnBtn.hidden = NO;
            allreturnBtn.alpha = 1;
        }
    }
}
- (void)doStoreBtnClick{
    if (_isFromGoods) {
        ShopDetailVC *vc = [[ShopDetailVC alloc]init];
        vc.toUserID = minstr([_shopDic valueForKey:@"uid"]);
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];
    }else{
        [self doReturn];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
